'use strict';

const uniIdCommon = require('uni-id-common');
const db = uniCloud.database();
const { getConfig } = require('uni-config-center');
const zhentouConfig = getConfig('zhentou-config');

// 管理员校验函数
async function checkAdmin(token, context) {
  if (!token) {
    throw new Error('Token不能为空');
  }

  try {
    // 使用 uni-id-common 验证 token
    const uniIdIns = uniIdCommon.createInstance({ context });
    const payload = await uniIdIns.checkToken(token);

    if (payload.errCode) {
      throw new Error(payload.errMsg || 'Token验证失败');
    }

    const uid = payload.uid;

    // 检查管理员权限
    if (!Array.isArray(zhentouConfig.admin_uids) || !zhentouConfig.admin_uids.includes(uid)) {
      throw new Error('权限不足，非管理员禁止访问');
    }

    return { uid };

  } catch (error) {
    console.error('管理员校验失败:', error);
    throw error;
  }
}


exports.main = async (event, context) => {
  const { action, params } = event;
  let result = {};

  try {
    // 所有操作前先校验管理员身份
    await checkAdmin(event.uniIdToken, context);
  } catch (e) {
    return { code: 403, message: e.message };
  }

  switch (action) {
    case 'getAllUsers':
      // 获取所有用户列表
      const usersRes = await db.collection('users')
        .field({
          _id: true,
          nickname: true,
          avatar_url: true,
          points: true,
          level_name: true,
          commission_available: true,
          commission_pending: true,
          commission_total: true,
          register_date: true
        })
        .orderBy('register_date', 'desc')
        .limit(100)
        .get();

      result = {
        code: 0,
        data: usersRes.data
      };
      break;

    case 'getSettings':
      const settingsRes = await db.collection('settings').where({ key: 'default' }).get();
      result = { code: 0, data: settingsRes.data[0] || {} };
      break;

    case 'updateSettings':
      const newSettings = params.settings;
      delete newSettings._id; // 防止更新_id
      await db.collection('settings').where({ key: 'default' }).update(newSettings);
      result = { code: 0, message: '配置更新成功' };
      break;

    case 'updateUser':
      const { userId, updates } = params;
      if (!userId || !updates) {
        throw new Error('参数不完整');
      }
      await db.collection('users').doc(userId).update(updates);
      result = { code: 0, message: '用户更新成功' };
      break;

    case 'getStats':
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const todayTimestamp = today.getTime();

      const totalUsers = await db.collection('users').count();
      const todayUsers = await db.collection('users').where({ register_date: db.command.gte(todayTimestamp) }).count();
      const pendingWithdrawals = await db.collection('withdrawals').where({ status: 'processing' }).count();

      result = {
        code: 0,
        data: {
          totalUsers: totalUsers.total,
          todayUsers: todayUsers.total,
          pendingWithdrawals: pendingWithdrawals.total
        }
      };
      break;

    case 'updateRules':
      const { rules } = params;
      if (!rules) {
        throw new Error('规则参数不能为空');
      }

      // 验证佣金规则格式
      if (rules.commission_rules && rules.commission_rules.levels) {
        const levels = rules.commission_rules.levels;
        if (!Array.isArray(levels) || levels.length !== 3) {
          throw new Error('佣金规则必须包含3个等级配置');
        }

        // 验证每个等级的必要字段
        const requiredFields = ['name', 'points_required', 'commission_rate'];
        for (let i = 0; i < levels.length; i++) {
          const level = levels[i];
          for (const field of requiredFields) {
            if (level[field] === undefined || level[field] === null) {
              throw new Error(`等级${i + 1}缺少必要字段: ${field}`);
            }
          }
          // 验证佣金比例范围
          if (level.commission_rate < 0 || level.commission_rate > 1) {
            throw new Error(`等级${i + 1}的佣金比例必须在0-1之间`);
          }
        }

        // 验证等级积分要求递增
        for (let i = 1; i < levels.length; i++) {
          if (levels[i].points_required <= levels[i-1].points_required) {
            throw new Error('等级积分要求必须递增');
          }
        }
      }

      await db.collection('settings').doc('rules').update(rules);
      result = { code: 0, message: '分销规则更新成功' };
      break;

    case 'getRules':
      const rulesRes = await db.collection('settings').doc('rules').get();
      if (rulesRes.data.length > 0) {
          result = { code: 0, data: rulesRes.data[0] };
      } else {
          result = { code: 0, data: {} }; // Return empty object if no rules set
      }
      break;

    default:
      result = {
        code: 403,
        message: '请求不受支持',
      };
      break;
  }

  return result;
};
